﻿using B.S.DataBase.Myproject.Helper;
using B.S.DataBase.MyProject.Domain.KnowledgeManagements;
using B.S.DataBase.MyProject.Domain.PatientMobileDevice;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
using MedicalPCTerminal.Read.API.Appcation.Commands.TroubleCommand;

namespace MedicalPCTerminal.Read.API.Appcation.CommandHandlers.TroubleCommandHandlers
{
    /// <summary>
    /// 聊天列表查询命令处理方法
    /// </summary>
    public class GetChatListItemCommandHandler:IRequestHandler<GetChatListItemCommand,APIResult<List<ChatListItem>>>
    {
        /// <summary>
        /// sugar
        /// </summary>
        private readonly SqlSugarContext sugar;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="sugar"></param>
        public GetChatListItemCommandHandler(SqlSugarContext sugar)
        {
            this.sugar = sugar;
        }
        /// <summary>
        /// 处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<List<ChatListItem>>> Handle(GetChatListItemCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<ChatListItem>> result = new APIResult<List<ChatListItem>>();
            try
            {
                var list = sugar.db.Queryable<ChatListItem>().Where(x => x.IsDel == false);

                // 按用户名和角色筛选
                if (request.UserName.IsNotNull() && request.Role != null)
                {
                    // 查询该用户的所有聊天记录
                    // 对于医生，查找医生发起的对话和发给医生的对话
                    // 对于患者，查找患者发起的对话和发给患者的对话
                    list = list.Where(x => (x.Sender == request.UserName && x.Role == request.Role) );
                }

                // 按特定患者ID筛选
                if (!string.IsNullOrEmpty(request.PatientId))
                {
                    list = list.Where(x => x.Sender == request.PatientId || x.ContactName == request.PatientId);
                }

                // 按聊天ID筛选
                if (request.ChatListItemID != null)
                {
                    list = list.Where(x => x.ChatListItemID == request.ChatListItemID);
                }

                // 按关键字搜索
                if (!string.IsNullOrEmpty(request.Keyword))
                {
                    list = list.Where(x => x.ContactName.Contains(request.Keyword) || 
                                          x.Sender.Contains(request.Keyword) || 
                                          x.ChatMessage.Contains(request.Keyword));
                }

                // 按会话分组，只获取每个会话的最新一条消息
                //var latestMessages = list
                //    .OrderByDescending(x => x.ChatTime)
                //    .ToList()
                //    .GroupBy(x => x.Sender == request.UserName ? x.ContactName : x.Sender)
                //    .Select(g => g.First())
                //    .OrderByDescending(x => x.ChatTime)
                //    .ToList();

                result.data = list.ToList();
                result.Code = APIEnum.查询成功;
                result.Msg = APIEnum.查询成功.ToString();
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"查询消息列表时发生异常: {ex.Message}");
                result.Code = APIEnum.查询失败;
                result.Msg = APIEnum.查询失败.ToString();
            }
            return await Task.FromResult(result);
        }
    }
}
